package com.xbjtech.shiro.realm;

import java.util.Date;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.xbjtech.model.MobileYzm;
import com.xbjtech.model.User;
import com.xbjtech.service.MobileYzmService;
import com.xbjtech.service.UserService;

public class MobileYzmRealm extends AuthorizingRealm {

	@Autowired
	MobileYzmService mobileYzmService;
	
	@Autowired
	UserService userService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
 		String mobile = (String) token.getPrincipal();
 		User user = userService.selectUserByMobile(mobile);
 		if (user == null) {
 			throw new AuthenticationException("手机号码不存在");
 		}
 		MobileYzm mobileYzm = mobileYzmService.findLastYzmByMobile(mobile);
		if (mobileYzm == null) {
			throw new AuthenticationException("没有验证码记录");
		}
		if (new Date().getTime() - mobileYzm.getCreateTime().getTime() > (2 * 60 * 1000) ) {
			throw new AuthenticationException("验证码失效");
		}
		
		return new SimpleAuthenticationInfo(user, mobileYzm.getCode(), getName());
	}

}
